import { Button, Form, Input, Select, message, Switch, Tree } from "antd";
import React, { Component } from "react";
import { mainRouter } from "../../../router/index";
import { roleAdd, roleUpdate } from "../../../api/system";

const { Option } = Select;
const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
  },
};
class RoleFrom extends Component {
  formRef = React.createRef();
  state = {
    checkArr: [],
  };
  componentDidMount = () => {
    console.log(this.props.roleInfo);
    const { roleInfo } = this.props;
    if (roleInfo) {
      this.formRef.current.setFieldsValue(roleInfo);
      this.setState({
        checkArr: roleInfo.power,
      });
    }
  };
  onFinish = async (values) => {
    const { roleInfo, handleFrom } = this.props;
    let id;
    if (roleInfo) {
      await roleUpdate(roleInfo.objectId, values);
      id = roleInfo.objectId;
    } else {
      const res = await roleAdd(values);
      //   console.log(res.data.objectId);
      id = res.data.objectId;
    }
    handleFrom(false, id, values);
  };
  onReset = () => {
    this.formRef.current.resetFields();
  };
  onCheck = (checkedKeys) => {
    console.log("onCheck", checkedKeys);
    this.formRef.current.setFieldsValue({
      power: checkedKeys,
    });
    this.setState({
      checkArr: checkedKeys,
    });
  };
  render() {
    const { roleInfo } = this.props;
    return (
      <div>
        <Form
          {...layout}
          ref={this.formRef}
          name="control-ref"
          onFinish={this.onFinish}
          initialValues={{
            grounding: false,
          }}
        >
          <Form.Item
            name="name"
            label="角色名称"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="power"
            label="菜单权限"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Tree
              checkable
              onCheck={this.onCheck}
              treeData={mainRouter}
              fieldNames={{ title: "label" }}
              checkedKeys={this.state.checkArr}
            />
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              {roleInfo ? "编辑" : "添加"}
            </Button>
            <Button
              htmlType="button"
              onClick={this.onReset}
              style={{ marginLeft: "10px" }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

export default RoleFrom;
